package com.lwp.demo.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kaka
 */
@Component
@WebFilter(filterName = "clientLoginFilter",urlPatterns = "/client/*")
public class ClientLoginFilter implements Filter {
    @Value("${server_host_port}")
    private String serverHostPort;
    @Value("${own_host_port}")
    private String ownHostPort;
    private Logger logger=LoggerFactory.getLogger(ClientLoginFilter.class);
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.debug("Client Filter Activated");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse) response;
        String systemUrl=ownHostPort+req.getRequestURI();

        //server返回token 再做验证
        String token = req.getParameter("token");
        if (token != null) {
            // 去sso认证中心校验token
            boolean verifyResult = this.verify(serverHostPort+systemUrl, token);
            if (!verifyResult) {
                logger.info("检验未通过，To:"+serverHostPort+"/server/login?systemUrl="+systemUrl);
                res.sendRedirect(serverHostPort+"/server/login?systemUrl="+systemUrl);
                return;
            }
            Cookie cookie = new Cookie("token",token);
            cookie.setMaxAge(1800);
            res.addCookie(cookie);
            chain.doFilter(request, response);
            return;
        }
        //客户端直接发起 查询cookie
        Cookie[] cookies = req.getCookies();
        if (cookies!=null&&cookies.length>0){
            for(Cookie cookie : cookies) {
                if("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    break;
                }
            }
        }
        //cookie里面有token
        if (token!=null){
            boolean verifyResult = this.verify(serverHostPort+systemUrl, token);
            if (!verifyResult) {
                logger.info("检验未通过，To:"+serverHostPort+"/server/login?systemUrl="+systemUrl);
                res.sendRedirect(serverHostPort+"/server/login?systemUrl="+systemUrl);
                return;
            }
            chain.doFilter(request, response);
            return;
        }

        //未登陆 跳转至sso认证中心
        logger.info("检验未通过，To:"+serverHostPort+"/server/login?systemUrl="+systemUrl);
        res.sendRedirect(serverHostPort+"/server/login?systemUrl="+systemUrl);
    }
    public  boolean verify(String systemUrl, String token){
        RestTemplate restTemplate=new RestTemplate();
        Map<String,String> params=new HashMap<>();
        params.put("token",token);
        ResponseEntity<String> responseEntity=restTemplate
                .getForEntity(serverHostPort+"/main/checkToken?token={token}",String.class,params);
        if (responseEntity.getBody()!=null)
        {
            return responseEntity.getBody().contains("true");
        }
        return false;
    }
}
